<?php
/**
 * | @author 韩威兵^life <1877361302@qq.com>
 * +----------------------------------------------------------------------
 * | @copyright 2016 - 2019 HQ
 * +----------------------------------------------------------------------
 * | @version $Id: 2019/4/27 11:38 jiahe_new FoodServer.php 韩威兵^life $
 * +----------------------------------------------------------------------
 */

namespace app\api\server\food;

use app\common\common\model\oldModel\goods\Goods;
use app\common\common\model\oldModel\goods\StoreGoods;
use app\common\common\model\oldModel\store\Store;
use app\common\common\model\oldModel\store\StoreExt;
use app\common\common\Server\commonServer;

class  FoodServer
{
    /**
     * 获取菜品列表，有可能是从redis中获取
     * @param $store_id
     * @param bool $update_status
     * @return array|mixed
     */
    public function getList($store_id, $update_status = false) {
        //redis需要的数据
        $redis_databases    = config('redis_database');
        $now_date           = date('H:i');
        $breakfast_time_arr = $this->getBreakfastTime($store_id);
        $dinner_timea_arr   = $this->getDinnerTime($store_id, $now_date);

        //判断现在时间在该门店下面，是早餐时间还是午餐时间，或者是其他时间。用作redis缓存区别
        if ($now_date >= $breakfast_time_arr['start'] && $now_date <= $breakfast_time_arr['end']) {
            $now_time_txt = 'breakfast';
        } elseif (($now_date >= $breakfast_time_arr['end'] || $now_date < $breakfast_time_arr['start']) && $dinner_timea_arr['dinner_status']) {
            $now_time_txt = 'dinner';
        } else {
            $now_time_txt = 'default';
        }

        $redis_key = 'index_goods_'.$now_time_txt.'_'.$store_id;
        //读取缓存
        $data = getRedis($redis_databases)->get($redis_key);

        //判断是否能读取缓存数据
        if (($data === false) || $update_status) {

            //门店数据
            $store_field = $this->getStoreFullInfoByStoreId($store_id);

            //根据店铺id获取商品信息
            $list              = $this->getStoreGoodsByStoreId($store_id, $store_field['is_breakfast']);
            $list['store']     = [
                'name'   => $store_field['sname'],
                'id'     => $store_field['store_id'],
                'status' => $store_field['status'],
                'field'  => $store_field,
            ];
            $list['tableware'] = config('tableware_price');
            //写入缓存
            getRedis($redis_databases)->setex($redis_key, 10800, json_encode($list));
        } else {
            $list = json_decode($data, true);
        }

        return $list;
    }


    /**
     * 获取门店信息
     * @param $storeId
     * @return array
     */
    public function getStoreFullInfoByStoreId($storeId) {
        //$store_ext_field = (new StoreExt())->findByWhere(['store_id'=>$storeId]);


        $store_field = (new Store())->findByStoreIdGetFull($storeId);
        //$store_ext_field = (new StoreExt())->findByWhere(['store_id'=>$storeId]);
        //$store_field['ext'] = $store_ext_field;

        return $store_field;
    }


    /**
     * 根据店铺查找商品
     * @param $storeId
     * @return array
     */
    public function getStoreGoodsByStoreId($storeId, $is_breakfast = 1) {
        $goods_model = new Goods();
        $list        = $goods_model->allStoreGoods($storeId);

        //获取新品半价数据
        $new_food_Half_list = $this->newFoodHalf($storeId);
        //awdd($new_food_Half_list);
        //合并半价数据
        $list = array_merge($list, $new_food_Half_list);


        $nowTime = date('H:i');
        //最终需要的数据
        $categorys_goods_arr     = [];
        $breakfast_goods_arr     = [];
        $breakfast_categorys_arr = [];
        $categorys_arr           = [];

        //处理特殊门店早餐时间
        $breakfast_time_arr = $this->getBreakfastTime($storeId);
        $breakfastEndTime   = $breakfast_time_arr['end'];
        $breakfastStartTime = $breakfast_time_arr['start'];

        //处理特殊门店正餐时间
        $dinner_data_arr = $this->getDinnerTime($storeId, $nowTime);
        //早餐分类的名称，有些门店不一样
        $breakfast_name = $dinner_data_arr['breakfast_name'];
        //是否是特殊门店
        $special_dinner_status = $dinner_data_arr['special_dinner_status'];
        //正餐的状态
        $dinner_status = $dinner_data_arr['dinner_status'];
        //读取的配置文件数据
        $spcial_store_dinner = $dinner_data_arr['spcial_store_dinner'];

        //现在的就餐时段文字
        $now_txt = ($nowTime >= $breakfastStartTime) && ($nowTime < $breakfastEndTime) ? '早餐' : '正餐';
        //读取特殊商品的配置文件
        $special_goods = config('special_goods_status');
        //查询店铺信息
        $store_ext_field = (new StoreExt())->findByWhere(['store_id' => $storeId]);

        //获取延迟上市门店id，并使用旧的分类
        $use_old_food_list_store_ids = config('use_old_food_list_store_id');
        //默认采用最新上市的数据
        $new_store_status = true;
        //判断是否是推迟上市的门店
        if (in_array($storeId, $use_old_food_list_store_ids)) {
            $new_store_status = false;
        }
        //获取最新菜品分类名称
        $new_food_categorys = config('new_food_category_name');

        foreach ($list as $k => $v) {

            //拼接商品分类
            $v['category_id'] = $v['goods_type_id'];

            //门店菜品图片
            $v['pic_name'] = $v['spic_name'] ? config('aliPicUrl').$v['spic_name'] : $v['pic'];
            if ($this->isContiune($v, $nowTime, $breakfastEndTime)) {
                continue;
            }
            //特殊门店特殊处理
            if ($special_dinner_status && array_key_exists('all_can_sale', $spcial_store_dinner[$storeId])) {

                $v['can_sale'] = $spcial_store_dinner[$storeId]['all_can_sale'];
                //todo aw:
            } else if (array_key_exists($v['gc_name'],$special_goods) && isset($special_goods[$v['gc_name']]['can_sale'])) {
                //特殊商品特殊处理
                if($v['did'] == '08003'){
                    aw_log(['特殊分类'],'food.log');
                }
                $v['can_sale'] = $special_goods[$v['gc_name']]['can_sale'];
            } else {

                $status = $this->isBreakfastBinnerStatus($v,
                    $now_txt,
                    $breakfast_name,
                    $store_ext_field,
                    $dinner_status
                );
                //不支持早餐的店铺删早餐数据
                if ($status === false) {
                    continue;
                }
            }

            $v['isSet'] = $v['is_setfood'];
            //把早餐放到单独的数据中，方便置顶
            if (($v['gc_name'] == $breakfast_name)) {
                $this->formatGoodsCategorysData($v, $breakfast_goods_arr, $breakfast_categorys_arr);
                continue;
            }


            //新品半价放到单独的数据中，正常的数据也是需要整理的
            if (isset($v['is_new_half']) && ($v['is_new_half'] == 1)) {

                $new_food_Half_arr[$v['goods_type_id']][] = $v;
                //菜品分类列表
                $new_food_Half_categorys_arr['id_'.$v['goods_type_id']]['id']          = $v['goods_type_id'];
                $new_food_Half_categorys_arr['id_'.$v['goods_type_id']]['category_id'] = $v['goods_type_id'];
                $new_food_Half_categorys_arr['id_'.$v['goods_type_id']]['name']        = $v['gc_name'];
                $new_food_Half_categorys_arr['id_'.$v['goods_type_id']]['sort']        = $v['c_sort'];
            }
            //除了早餐的其他数据
            $this->formatGoodsCategorysData($v, $categorys_goods_arr, $categorys_arr);
        }
        //门店禁用早餐了不能显示早餐
        if ($is_breakfast == 0) {
            $breakfast_goods_arr     = [];
            $breakfast_categorys_arr = [];
        }
        //把新品半价放到数据的最前面
        if (isset($new_food_Half_arr) && isset($new_food_Half_categorys_arr)) {
            $breakfast_categorys_arr = $new_food_Half_categorys_arr + $breakfast_categorys_arr;
            $breakfast_goods_arr     = $new_food_Half_arr + $breakfast_goods_arr;
        }
        //把早餐数据放到数据的最前面
        $categorys_goods_arr = $breakfast_goods_arr + $categorys_goods_arr;
        $categorys_arr       = $breakfast_categorys_arr + $categorys_arr;

        return ['goods' => $categorys_goods_arr, 'categorys' => $categorys_arr];
    }


    /**
     * 为你推荐 、 每日半价
     */
    public function newFoodHalf($store_id) {
        $where = [
            'status'         => 1,
            'recommend_sort' => array('in', '1,2,3'),
            'store_id'       => $store_id,
            'stock'          => ['gt', 0],
            'is_meal'        => 1,
        ];

        $store_goods = new StoreGoods();
        $goods_field = $store_goods->allByWhere($where, 'update_time desc');


        //排除重复商品的问题
        $goods_ids = array_column($goods_field, 'dishsno');
        $new_goods = array_combine($goods_ids, $goods_field);

        //只取两个值
        $recommend_sorts = array_column($new_goods, 'recommend_sort');
        $new_goods       = array_combine($recommend_sorts, $new_goods);

        //取速记码
        $dishsno_arr = array_column($new_goods, 'dishsno');
        $dishsnos    = implode(',', $dishsno_arr);
        $sg_ids_arr  = array_column($new_goods, 'id');
        $sg_ids      = implode(',', $sg_ids_arr);

        $goods_model = new Goods();

        $arr = $goods_model->allStoreGoodsByDishsno($dishsnos, $sg_ids);

        $sort_arr = array();
        foreach ($arr as $k=>&$v){
            $sort_arr[] = $v['recommend_sort'];
            $v['gc_name']       = '店长推荐';
            $v['goods_type_id'] = 0;
            $v['is_new_half']   = 1;
        }
        array_multisort($sort_arr, SORT_DESC, $arr);

        return $arr;
    }


    /**
     * 查询是否需要跟新数据，false 无需跟新，读取缓存数据即可，true  需要跟新缓存数据。
     * @return bool
     */
    public function isUpdateGoods() {
        $update_goods_end_time = config('update_goods_end_time');
        if (time() > strtotime($update_goods_end_time)) {
            return false;
        }

        return true;
    }


    /**
     * 判断早餐和正餐能不能买
     * @param $v
     * @param $now_txt
     * @param $breakfast_name
     * @param $store_ext_field
     * @param $dinner_status
     * @return bool
     */
    public function isBreakfastBinnerStatus(&$v, $now_txt, $breakfast_name, $store_ext_field, $dinner_status) {
        //普通门店,普通商品
        if (('早餐' == $now_txt) && ($v['gc_name'] == $breakfast_name)) {
            //不支持早餐的店铺删除数据
            if (!$store_ext_field['is_breakfast']) {
                return false;
            }
            //早餐时间段买早餐
            $v['can_sale'] = 1;
        } elseif ('正餐' == $now_txt && $dinner_status && ($v['gc_name'] != $breakfast_name)) {
            //正餐时间段只能买正餐
            $v['can_sale'] = 1;
        } else {
            //其他情况都不可以买
            $v['can_sale'] = 0;
        }

        return true;
    }


    /**
     * 组装需要的数据
     * @param $v
     * @param $categorys_goods_arr
     * @param $categorys_arr
     * @return bool
     */
    public function formatGoodsCategorysData($v, &$categorys_goods_arr, &$categorys_arr) {
        //$new_data['name'] = $v['name'];
        //$new_data['id'] = $v['goods_id'];
        //$new_data['can_sale'] = $v['can_sale'];
        //$new_data['pic'] = $v['pic'];
        //$new_data['price'] = $v['price'];
        //$new_data['current_price'] = $v['current_price'];
        //$new_data['did'] = $v['did'];
        //$new_data['amdkid'] = $v['amdkid'];
        //
        //$new_data['classify_id'] = $v['goods_id'];
        //$new_data['classify_name'] = $v['gc_name'];
        //菜品数据
        //        $categorys_goods_arr[$v['goods_type_id']][] = $v;
        if($v['goods_type_id'] != 0){
            $categorys_goods_arr[$v['did']] = $v;
        }
        //菜品分类列表
        $categorys_arr['id_'.$v['goods_type_id']]['id']          = $v['goods_type_id'];
        $categorys_arr['id_'.$v['goods_type_id']]['category_id'] = $v['goods_type_id'];
        $categorys_arr['id_'.$v['goods_type_id']]['name']        = $v['gc_name'];
        $categorys_arr['id_'.$v['goods_type_id']]['sort']        = $v['c_sort'];


        //菜品数据
        //$breakfast_goods_arr[$v['goods_type_id']][] = $v;
        ////菜品分类列表
        //$breakfast_categorys_arr[$v['goods_type_id']]['id']   = $v['goods_type_id'];
        //$breakfast_categorys_arr[$v['goods_type_id']]['name'] = $v['gc_name'];
        //$breakfast_categorys_arr[$v['goods_type_id']]['sort'] = $v['c_sort'];

        //菜品数据
        //$categorys_goods_arr[$v['goods_type_id']][] = $v;
        ////菜品分类列表
        //$categorys_arr[$v['goods_type_id']]['id']   = $v['goods_type_id'];
        //$categorys_arr[$v['goods_type_id']]['name'] = $v['gc_name'];
        //$categorys_arr[$v['goods_type_id']]['sort'] = $v['c_sort'];
        return true;
    }


    /**
     * 是否跳过循环
     * @param $v
     * @param $nowTime
     * @param $breakfastEndTime
     * @return bool
     */
    public function isContiune($v, $nowTime, $breakfastEndTime) {
        //过滤  筷子, 积分商城的物品
        if (($v['did'] == '28933') || ($v['gc_name'] == '积分商城')) {
            return true;
        }
        //判断 如果优惠福利不满足条件不展示
        if (($v['gc_name'] == '优惠福利') && ($nowTime < $breakfastEndTime)) {
            return true;
        }

        //获取最新菜品分类名称
        $new_food_categorys = config('new_food_category_name');

        return false;
    }


    /**
     * 获取早餐开始和结束时间
     * @param $storeId
     * @return array
     */
    public function getBreakfastTime($storeId) {
        $spcial_store_breakfast = config('special_store_breakfast');
        if (array_key_exists($storeId, $spcial_store_breakfast)) {
            $breakfastEndTime   = $spcial_store_breakfast[$storeId]['end'];
            $breakfastStartTime = $spcial_store_breakfast[$storeId]['start'];
        } else {
            //周六日的早餐结束时间不一样
            $default_breakfast = config('default_breakfast');
            $week              = date('w');
            if ($week == 0 || $week == 6) {
                $breakfastEndTime   = $default_breakfast['weekend']['end'];
                $breakfastStartTime = $default_breakfast['weekend']['start'];
            } else {
                $breakfastEndTime   = $default_breakfast['working']['end'];
                $breakfastStartTime = $default_breakfast['working']['start'];
            }
        }

        return ['end' => $breakfastEndTime, 'start' => $breakfastStartTime];
    }


    /**
     * 获取正餐还有一些配置文件的信息
     * @param $storeId
     * @param $nowTime
     */
    public function getDinnerTime($storeId, $nowTime) {

        $dinner_end_time       = '23:59';
        $breakfast_name        = '自助早餐';
        $special_dinner_status = 0;
        $dinner_status         = true;

        $spcial_store_dinner = config('special_store_other');
        //判断店铺在不在正餐的特殊门店内
        if (array_key_exists($storeId, $spcial_store_dinner)) {
            if (array_key_exists('dinner_end', $spcial_store_dinner[$storeId])) {
                $dinner_end_time = $spcial_store_dinner[$storeId]['dinner_end'];
                $dinner_status   = $nowTime < $dinner_end_time;
            }
            if (array_key_exists('breakfast_name', $spcial_store_dinner[$storeId])) {
                $breakfast_name = $spcial_store_dinner[$storeId]['breakfast_name'];
            }
            $special_dinner_status = 1;
        }

        return [
            'dinner_status'         => $dinner_status,
            'special_dinner_status' => $special_dinner_status,
            'breakfast_name'        => $breakfast_name,
            'spcial_store_dinner'   => $spcial_store_dinner,
        ];
    }
}